import {Page, PageDelegate} from "./Page.js";
import EventBridge from "./EventBridge.js";
import Logger from "./Logger.js";

const PageEvent = {

    //subscribe
    SetData: "onSetData",

    //publish
    PageInited: "Page_onViewInitialized",
    PageReady: "Page_onReady",
    PageEvent: "Page_onEvent",
};


// wrapper event routing for running in web view control
export class WebViewPage
{
    constructor(data, template, css) {

        this.id = WebViewPage.getPageID();
        this._initEvent();

        this.pageHandler = new PageDelegate();

        this.pageHandler.onInited = this._onPageInited.bind(this);
        this.pageHandler.onReady = this._onPageReady.bind(this);
        this.pageHandler.onPageEvent = this._onPageEvent.bind(this);

        this.page = new Page(null, data, template, css, this.pageHandler);
    }

    static getPageID() {
        if (!WebViewPage._nextID) {
            WebViewPage._nextID = 1;
        }
        return WebViewPage._nextID++;
    }

    getID() {
        return this.id;
    }

    getPage() {
        return this.page;
    }

    _initEvent() {

    }

    _onPageInited() {
        console.log("notify 'onPageLoad'");
        EventBridge.postMessage(PageEvent.PageInited, {});
    }

    _onPageReady() {
        console.log("notify 'onPageReady'");
        EventBridge.postMessage(PageEvent.PageReady, {});
    }

    setPageData(data) {
        this.page.setData(data);
    }

    _onPageEvent(event) {
        let param = {
            name: PageEvent.PageEvent,
            data: {
                name: event.callback,
                data: event.data
            }
        };
        console.log("Page.onPageEvent, event=" + JSON.stringify(param));
        EventBridge.postMessage(PageEvent.PageEvent, param);
    }
}

export class WebViewPageMgr
{
    static instance() {
        if (!WebViewPageMgr._instance) {
            WebViewPageMgr._instance = new WebViewPageMgr();
        }
        return WebViewPageMgr._instance;
    }

    constructor() {
        this.pages = [];
    }

    createPage(template, css) {
        let page = new WebViewPage(null, template, css);
        this.pages.push(page);

        //register event callback
        EventBridge.subscribe(PageEvent.SetData + EventBridge.getWebViewID(), "view.WebViewPageMgr.__OnPageSetData");

        //create page
        page.getPage().create();

        return page;
    }

    getPage() {
        if (this.pages.length > 0) {
            return this.pages[0];
        }
        return null;
    }

    static __OnPageSetData(data) {
        Logger.logNotice("OnPageSetData: " + JSON.stringify(data));

        let page = WebViewPageMgr.instance().getPage();
        page.setPageData(data.data);
    }
}

export function createWebViewPage(template, style) {

    return WebViewPageMgr.instance().createPage(template, style);
}
